﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using TagThisOrgProject.Models;

namespace TagThisOrgProject.Repository
{
    public class BookmarkRepository
    {
        public BookmarkRepository(TagContext context)
        {
            this.Context = context;
        }
        public TagContext Context { get; set; }
        public UrlRepository UrlRepository { get; set; }
        public TagRepository TagRepository { get; set; }

        public List<Bookmark> AddBookmarks(string url, bool isPrivate, params string[] tags)
        {
            var bookmarks = new List<Bookmark>();

            //Получаем необходимые репозитории
            if (UrlRepository == null)
                this.UrlRepository = new Repository.UrlRepository(this.Context);
            if (TagRepository == null)
                this.TagRepository = new Repository.TagRepository(this.Context);
            //Получаем Url
            var urlForAdd = this.UrlRepository.AddUrl(url);
            //получаем теги
            var tagsDB = TagRepository.AddTags(tags);
            //проверяем на наличие закладок в БД
            var bkmrksInDB = GetBookmarks(urlForAdd, tagsDB.ToArray());
            //обрабатываем все теги
            foreach (var tag in tagsDB)
            {
                //проверяем есть ли конкретно эта закладка в БД
                var bookmarkForAdding = (from b in bkmrksInDB  where b.TagId == tag.TagId select b).FirstOrDefault(); //GetBookmark( urlForAdd, tag);
                if (bookmarkForAdding != null)
                {
                    if (bookmarkForAdding.isPrivate)
                    {
                        bookmarkForAdding.isPrivate = isPrivate;
                    }
                }
                else
                {
                    bookmarkForAdding = Context.Bookmarks.Add(new Bookmark { TagId = tag.TagId, UrlId = urlForAdd.UrlId, isPrivate = isPrivate });
                }
                bookmarks.Add(bookmarkForAdding);
            }
            try
            {
                    Context.SaveChanges();
            }
            catch
            {
                throw new Exception("Ошибка сохранения закладки. Код 0003");
            }
            return bookmarks;
        }
        public Bookmark GetBookmark(Url u, Tag t)
        {
            var bookmark = (from b in this.Context.Bookmarks
                            where b.TagId == t.TagId &&
                            u.UrlId == b.UrlId
                            select b).FirstOrDefault();
            return bookmark;
        }
        public Bookmark GetBookmark(Int64 id)
        {
            return (from b in Context.Bookmarks
                    where b.BookmarkId == id
                    select b).FirstOrDefault();
        }
        public IEnumerable<Bookmark> GetBookmarks(Url u, params Tag[] tags)
        {
            var tagIds = tags.Select(t => t.TagId);
            return (from b in this.Context.Bookmarks
                    where u.UrlId == b.UrlId && tagIds.Contains(b.TagId)
                    select b).ToList();
        }
        public Bookmark DeleteBookmark(int id)
        {
            var b = GetBookmark(id);
            if (b != null)
                Context.Bookmarks.Remove(b);
            return b;
        }
        public IEnumerable<Bookmark> GetPublicBookmarks(params Tag[] tags)
        {
            return tags.SelectMany(t => t.Bookmarks).Where(b => !b.isPrivate);
            //return ( from b in Context.Bookmarks
            //             where !b.isPrivate && tags.Contains(b.Tag)
            //             select b);
        }
    }
}